import React, { forwardRef, useEffect, useImperativeHandle } from 'react'
import { Chart } from '@antv/g2'

const G2BaseChart = forwardRef(
  (
    { data, width = '100%', height = 190, options = {}, render, onReady },
    ref
  ) => {
    const containerRef = React.useRef()
    const chartInstance = React.useRef()

    // 初始化图表
    useEffect(() => {
      if (!containerRef.current) return

      chartInstance.current = new Chart({
        container: containerRef.current,
        autoFit: true,
        width: parseInt(width),
        height: parseInt(height),
        ...options,
      })

      if (typeof render === 'function') {
        render(chartInstance.current)
      } else {
        chartInstance.current.data(data)
        chartInstance.current.render()
      }

      if (onReady) onReady(chartInstance.current)

      return () => chartInstance.current?.destroy()
    }, [])

    // 数据更新处理
    useEffect(() => {
      if (!chartInstance.current || !data) return
      chartInstance.current.changeData(data)
    }, [data])

    // 暴露实例方法
    useImperativeHandle(ref, () => ({
      getInstance: () => chartInstance.current,
      download: (name = 'chart') => chartInstance.current?.downloadImage(name),
    }))

    return <div ref={containerRef} style={{ width, height }} />
  }
)

export default G2BaseChart
